// EmailLogin 组件的业务逻辑函数

// 导入 HTML 模板
export { render } from './html.js';

// 导入请求工具
import request from '../../../utils/request.js';
import {localStore} from "../../../Store/localStore";
import {renderLogin} from "../../common/renderLogin.js";

/**
 * 绑定事件监听器
 * @param {EmailLogin} component - 组件实例
 */
export function bindEvents(component) {
    const registerAccount = component.shadowRoot.querySelector('#registerAccount');
    const loginModal = component.shadowRoot.getElementById('loginModal');
    const closeBtn = component.shadowRoot.getElementById('closeBtn');
    const loginForm = component.shadowRoot.getElementById('loginForm');
    const emailInput = component.shadowRoot.getElementById('loginEmail');
    const passwordInput = component.shadowRoot.getElementById('loginPassword');
    const captchaInput = component.shadowRoot.getElementById('loginCaptcha');
    const captchaImage = component.shadowRoot.getElementById('captchaImage');
    const refreshCaptcha = component.shadowRoot.getElementById('refreshCaptcha');
    const forgotPassword = component.shadowRoot.getElementById('forgotPassword');
    const googleLogin = component.shadowRoot.getElementById('googleLogin');
    const githubLogin = component.shadowRoot.getElementById('githubLogin');

    // 绑定切换到注册组件的事件
    registerAccount.addEventListener('click', (e) => {
        const app = document.querySelector('#app');
        const container = document.querySelector('#container');
        const er = container.querySelector('email-register');
        const emailRegister = document.importNode(er,true);


        app.appendChild(emailRegister);
        emailRegister.open();
        app.removeChild(component);
    });

    // 关闭登录弹窗
    closeBtn.addEventListener('click', () => {
        closeModal(component);
    });

    // 点击背景关闭弹窗
    // loginModal.addEventListener('click', (e) => {
    //     if (e.target === loginModal) {
    //         closeModal(component);
    //     }
    // });

    // ESC键关闭弹窗
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && component.isOpen) {
            closeModal(component);
        }
    });

    // 表单提交
    loginForm.addEventListener('submit', (e) => {
        e.preventDefault();
        handleLogin(component);
    });

    // 实时验证
    emailInput.addEventListener('sl-input', () => {
        validateEmail(component);
    });

    passwordInput.addEventListener('sl-input', () => {
        validatePassword(component);
    });

    // 验证码输入验证
    captchaInput.addEventListener('sl-input', () => {
        validateCaptcha(component);
    });

    // 刷新验证码
    refreshCaptcha.addEventListener('click', () => {
        loadCaptcha(component);
    });

    // 点击验证码图片刷新
    captchaImage.addEventListener('click', () => {
        loadCaptcha(component);
    });

    // 忘记密码
    forgotPassword.addEventListener('click', (e) => {
        e.preventDefault();
        handleForgotPassword(component);
    });

    // 社交登录
    googleLogin.addEventListener('click', () => {
        handleSocialLogin(component, 'google');
    });

    githubLogin.addEventListener('click', () => {
        handleSocialLogin(component, 'github');
    });
}

/**
 * 打开模态框
 * @param {EmailLogin} component - 组件实例
 */
export function openModal(component) {
    component.isOpen = true;
    const modal = component.shadowRoot.getElementById('loginModal');
    modal.classList.add('show');
    
    // 加载验证码
    loadCaptcha(component);
    
    // 聚焦到邮箱输入框
    setTimeout(() => {
        const emailInput = component.shadowRoot.getElementById('loginEmail');
        emailInput.focus();
    }, 300);

    // 触发自定义事件
    component.dispatchEvent(new CustomEvent('modal-opened', {
        bubbles: true,
        detail: { component: 'email-login' }
    }));
}

/**
 * 关闭模态框
 * @param {EmailLogin} component - 组件实例
 */
export function closeModal(component) {
    component.isOpen = false;
    const modal = component.shadowRoot.getElementById('loginModal');
    modal.classList.remove('show');
    
    // 清除错误信息
    clearErrors(component);
    
    // 重置表单
    resetForm(component);

    // 触发自定义事件
    component.dispatchEvent(new CustomEvent('modal-closed', {
        bubbles: true,
        detail: { component: 'email-login' }
    }));

    // 真实的dom中找到email-login，将其删除
    document.querySelector('#email-login').remove();
}

/**
 * 处理登录逻辑
 * @param {EmailLogin} component - 组件实例
 */
export async function handleLogin(component) {
    if (component.isLoading) return;

    // 验证表单
    if (!validateForm(component)) {
        return;
    }

    setLoading(component, true);

    try {
        // 获取表单数据
        const email = component.shadowRoot.getElementById('loginEmail').value;
        const password = component.shadowRoot.getElementById('loginPassword').value;
        const captcha = component.shadowRoot.getElementById('loginCaptcha').value;

        // 调用真实的登录API
        await performLogin(email, password, captcha);

        // 登录成功
        handleLoginSuccess(component, { email });

    } catch (error) {
        handleLoginError(component, error.message);
    } finally {
        setLoading(component, false);
    }
}

/**
 * 模拟登录请求
 * @param {string} email - 邮箱
 * @param {string} password - 密码
 * @returns {Promise} 登录结果
 */
export async function simulateLogin(email, password) {
    // 模拟网络请求延迟
    await new Promise(resolve => setTimeout(resolve, 1500));

    // 简单的验证逻辑（实际项目中应该调用真实的API）
    if (email === 'demo@example.com' && password === '123456') {
        return { success: true, user: { email, name: 'Demo User' } };
    } else {
        throw new Error('邮箱或密码错误');
    }
}

/**
 * 处理登录成功
 * @param {EmailLogin} component - 组件实例
 * @param {Object} userData - 用户数据
 */
export function handleLoginSuccess(component, userData) {
    // 触发登录成功事件
    component.dispatchEvent(new CustomEvent('login-success', {
        bubbles: true,
        detail: { user: userData }
    }));

    // 关闭弹窗
    closeModal(component);

    // 显示成功消息（可以通过事件让父组件处理）
    // console.log('登录成功:', userData);
}

/**
 * 处理登录错误
 * @param {EmailLogin} component - 组件实例
 * @param {string} message - 错误消息
 */
export function handleLoginError(component, message) {
    // 显示错误信息
    const emailError = component.shadowRoot.getElementById('loginEmailError');
    emailError.textContent = message;
    emailError.classList.add('show');

    // 触发登录失败事件
    component.dispatchEvent(new CustomEvent('login-error', {
        bubbles: true,
        detail: { message }
    }));
}

/**
 * 处理忘记密码
 * @param {EmailLogin} component - 组件实例
 */
export function handleForgotPassword(component) {
    // 触发忘记密码事件
    component.dispatchEvent(new CustomEvent('forgot-password', {
        bubbles: true,
        detail: { component: 'email-login' }
    }));

    // console.log('忘记密码功能');
}

/**
 * 处理社交登录
 * @param {EmailLogin} component - 组件实例
 * @param {string} provider - 登录提供商
 */
export function handleSocialLogin(component, provider) {
    // 触发社交登录事件
    component.dispatchEvent(new CustomEvent('social-login', {
        bubbles: true,
        detail: { provider }
    }));

    // console.log(`${provider} 登录`);
}

/**
 * 验证表单
 * @param {EmailLogin} component - 组件实例
 * @returns {boolean} 验证结果
 */
export function validateForm(component) {
    const isEmailValid = validateEmail(component);
    const isPasswordValid = validatePassword(component);
    const isCaptchaValid = validateCaptcha(component);
    return isEmailValid && isPasswordValid && isCaptchaValid;
}

/**
 * 验证邮箱
 * @param {EmailLogin} component - 组件实例
 * @returns {boolean} 验证结果
 */
export function validateEmail(component) {
    const emailInput = component.shadowRoot.getElementById('loginEmail');
    const emailError = component.shadowRoot.getElementById('loginEmailError');
    const email = emailInput.value.trim();

    if (!email) {
        showError(emailError, '请输入邮箱地址');
        return false;
    }

    const emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
    if (!emailRegex.test(email)) {
        showError(emailError, '邮箱格式不正确，请及时更正');
        return false;
    }

    hideError(emailError);
    return true;
}

/**
 * 验证密码
 * @param {EmailLogin} component - 组件实例
 * @returns {boolean} 验证结果
 */
export function validatePassword(component) {
    const passwordInput = component.shadowRoot.getElementById('loginPassword');
    const passwordError = component.shadowRoot.getElementById('loginPasswordError');
    const password = passwordInput.value;

    if (!password) {
        showError(passwordError, '请输入密码');
        return false;
    }

    // 密码格式验证：至少8位，必须包含大小写字母、数字和特殊字符
    const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&.])[A-Za-z\d@$!%*#?&_.]{8,}$/;
    if (!passwordRegex.test(password)) {
        showError(passwordError, '密码至少8位，必须包含字母和数字,和@$!%*#?&_.');
        return false;
    }

    hideError(passwordError);
    return true;
}

/**
 * 显示错误信息
 * @param {HTMLElement} errorElement - 错误元素
 * @param {string} message - 错误消息
 */
export function showError(errorElement, message) {
    errorElement.textContent = message;
    errorElement.classList.add('show');
}

/**
 * 隐藏错误信息
 * @param {HTMLElement} errorElement - 错误元素
 */
export function hideError(errorElement) {
    errorElement.classList.remove('show');
}

/**
 * 清除所有错误信息
 * @param {EmailLogin} component - 组件实例
 */
export function clearErrors(component) {
    const errors = component.shadowRoot.querySelectorAll('.error-message');
    errors.forEach(error => {
        error.classList.remove('show');
    });
}

/**
 * 重置表单
 * @param {EmailLogin} component - 组件实例
 */
export function resetForm(component) {
    const form = component.shadowRoot.getElementById('loginForm');
    form.reset();
}

/**
 * 设置加载状态
 * @param {EmailLogin} component - 组件实例
 * @param {boolean} loading - 是否加载中
 */
export function setLoading(component, loading) {
    component.isLoading = loading;
    const submitBtn = component.shadowRoot.getElementById('submitBtn');
    const formContainer = component.shadowRoot.querySelector('.login-form-container');

    if (loading) {
        submitBtn.loading = true;
        submitBtn.textContent = '登录中...';
        formContainer.classList.add('loading');
    } else {
        submitBtn.loading = false;
        submitBtn.innerHTML = '<sl-icon name="box-arrow-in-right" slot="prefix"></sl-icon>登录';
        formContainer.classList.remove('loading');
    }
}

/**
 * 验证验证码
 * @param {EmailLogin} component - 组件实例
 * @returns {boolean} 验证结果
 */
export function validateCaptcha(component) {
    const captchaInput = component.shadowRoot.getElementById('loginCaptcha');
    const captchaError = component.shadowRoot.getElementById('loginCaptchaError');
    const captcha = captchaInput.value.trim();

    if (!captcha) {
        showError(captchaError, '请输入验证码');
        return false;
    }

    hideError(captchaError);
    return true;
}

/**
 * 加载验证码图片
 * @param {EmailLogin} component - 组件实例
 */
export async function loadCaptcha(component) {
    try {
        const captchaImage = component.shadowRoot.getElementById('captchaImage');
        const refreshBtn = component.shadowRoot.getElementById('refreshCaptcha');
        
        // 设置加载状态
        refreshBtn.loading = true;
        captchaImage.style.opacity = '0.5';
        
        // 从cookie中获取UUID
        const uuid = getCookie('uuid');
        console.log('🔍 前端读取到的UUID:', uuid);
        console.log('🍪 当前所有cookies:', document.cookie);
        
        // 构建请求头
        const headers = {};
        if (uuid) {
            headers['uuid'] = uuid;
            console.log('✅ 将UUID设置到请求头:', uuid);
        } else {
            console.log('❌ 没有找到UUID cookie');
        }
        
        // 使用 axios request 调用后端API获取验证码
        const response = await request.get('/users/captcha', {
            headers: headers,
            withCredentials: true, // 包含cookie
            responseType: 'blob' // 指定响应类型为blob
        });
        
        // axios 成功响应时，数据在 response.data 中
        const blob = response.data;
        const imageUrl = URL.createObjectURL(blob);
        
        captchaImage.src = imageUrl; //放置带src中
        
        // 清理之前的URL
        if (component.captchaUrl) {
            URL.revokeObjectURL(component.captchaUrl);
        }
        component.captchaUrl = imageUrl;
        
    } catch (error) {
        console.error('加载验证码失败:', error);
        const captchaError = component.shadowRoot.getElementById('loginCaptchaError');
        showError(captchaError, '验证码加载失败，请刷新重试');
    } finally {
        const captchaImage = component.shadowRoot.getElementById('captchaImage');
        const refreshBtn = component.shadowRoot.getElementById('refreshCaptcha');
        refreshBtn.loading = false;
        captchaImage.style.opacity = '1';
    }
}

/**
 * 执行登录请求
 * @param {string} email - 邮箱
 * @param {string} password - 密码
 * @param {string} captcha - 验证码
 */
export async function performLogin(email, password, captcha) {
    const response = await request.post('/users/sign-in', {
        mail: email,
        pass: password,
        code: captcha
    }, {
        withCredentials: true  //自动携带cookie
    });


    const result = response.data;
    
    if (result.code !== 0) {
        throw new Error(result.message || '登录失败');
    }

    //加入没有问题 ， 登录是成功的
    //将token存储到 localStorage
    //将用户的基本信息 存储 到localStorage
    //以后关闭浏览器 ， 再开启浏览器 ，NavBar 检测 localStorage 中 有没有 token
    //如果有token 还需要将 token 发送到 自动登录接口 (有可能过期)

    localStore.set("token",result.data.token);
    localStore.set("userinfo",result.data.user);

    //登录以后渲染从新渲染
    renderLogin();

    return result;
}

/**
 * 获取指定名称的Cookie值
 * @param {string} name - Cookie名称
 * @returns {string|null} Cookie值，如果不存在则返回null
 */
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) {
        return parts.pop().split(';').shift();
    }
    return null;
}